package com.zd.service.user.impl;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.zd.domain.User;
import com.zd.mapper.UserMapper;
import com.zd.service.SmsService;
import com.zd.service.user.UserService;
import com.zd.utils.AESUtils;
import com.zd.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 查看全部用户
     * @return
     */
    @Override
    public List<User> list() {
        return userMapper.list();
    }

    /**
     * 登录
     * @param username
     * @param userPassword
     * @return
     */
    @Override
    public User login(String username, String userPassword) {
        User user1 = null;

        User user = userMapper.findByUsername(username);

        if (user != null){
            //使用存储的密钥解密密码
            SecretKey secretKey = new SecretKeySpec(user.getUserKey(), "AES");

            String decryptedPassword = null;
            try {
                decryptedPassword = AESUtils.decryptPassword(user.getUserPassword(), secretKey);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            System.out.println("解密后的密码="+decryptedPassword);

            //如果输入的密码与数据库密码相同,则登录成功，返回用户信息
            if (userPassword.equals(decryptedPassword)){

                //用户名和密码输入正确后，创建token，并将coken存入user中，当token过滤器在过滤时，可以拿到这两个token进行是否放行操作
                String token = JWTUtils.createJWT(1000*60*30,user.getId());

                String longToken = JWTUtils.createJWT(1000*60*60*24*7,user.getId());

                user.setToken(token);
                user.setLongToken(longToken);

                user1 = user;

            }
        }


        return user1;

    }

    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public int register(User user){

        int i = 0;

        //查找是否存在该手机号
        User user1 = userMapper.findByPhone(user.getPhone());
        if (user1 == null){
            //查看手机验证码是否正确
            Map<String,Object> map = (Map<String, Object>) redisTemplate.boundValueOps(user.getPhone()).get();

            if (map != null){
                String codeStr = (String) map.get("codeStr");
                System.out.println("redis中的codestr========="+codeStr);

                SmsService smsService = new SmsService();

                if ((user.getCodeStr() != null) && (codeStr != null)){
                    boolean isSuccess = smsService.verifyCode(user.getCodeStr(), codeStr);


                    if (isSuccess){

                        //查找是否已经注册过相同账号
                        User findUser = userMapper.findByUsername(user.getUsername());


                        if (findUser == null){

                            //生成密钥
                            SecretKey secretKey = null;
                            try {
                                secretKey = AESUtils.generateAESKey();
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }

                            //用户密码加密
                            String encryptedPassword = null;
                            try {
                                encryptedPassword = AESUtils.encryptPassword(user.getUserPassword(), secretKey);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }

                            user.setUserKey(secretKey.getEncoded());
                            user.setUserPassword(encryptedPassword);

                            int register = userMapper.register(user);

                            i = register;
                        }

                    }
                }
            }
        }
        return i;
    }

    /**
     * 根据id查用户
     * @param userID
     * @return
     */
    @Override
    public User findByUserID(Integer userID) {
        return userMapper.findByUserID(userID);
    }



    /**
     * 修改密码
     * @param username
     * @param oldUserPassword
     * @param newUserPassword
     * @return
     */
    @Override
    public int updatePassword(String username, String oldUserPassword,String newUserPassword) {

        int i = 0;

        //查询用户
        User user = userMapper.findByUsername(username);

        if (user != null){
            //使用存储的密钥解密密码
            SecretKey secretKey = new SecretKeySpec(user.getUserKey(), "AES");

            String decryptedPassword = null;
            try {
                decryptedPassword = AESUtils.decryptPassword(user.getUserPassword(), secretKey);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }


            //如果解密后的密码与用户输入的原密码一致，则允许修改密码
            if (decryptedPassword.equals(oldUserPassword)){


                //生成密钥
                SecretKey secretKey1 = null;

                try {
                    secretKey1 = AESUtils.generateAESKey();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                //新密码
                String encryptedPassword = null;

                try {
                    //加密新密码
                    encryptedPassword = AESUtils.encryptPassword(newUserPassword, secretKey1);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                //修改密码
                i = userMapper.updatePassword(username, secretKey1.getEncoded(), encryptedPassword);

            }
        }

        return i;
    }

    /**
     * 修改绑定的手机号
     * @param username
     * @param newPhone
     * @return
     */
    @Override
    public int updatePhone(String username, String newPhone) {

        return userMapper.updatePhone(username,newPhone);
    }

    /**
     * 根据电话查对象
     * @param phone
     * @return
     */
    @Override
    public User findByPhone(String phone) {

        return userMapper.findByPhone(phone);

    }

    /**
     * 修改用户头像
     * @param user
     * @return
     */
    @Override
    public int updateUserImg(User user) {
        return userMapper.updateUserImg(user);
    }

    @Override
    public User findPhone(String phone) {
        return userMapper.findPhone(phone);
    }

    //根据用户名查找用户
    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    //验证原密码是否与输入的密码一致
    @Override
    public boolean findOldPassword(String username, String oldUserPassword) {

        boolean isTrue = false;

        User user = findByUsername(username);
        if (user != null){

            //解密
            //使用存储的密钥解密密码
            SecretKey secretKey = new SecretKeySpec(user.getUserKey(), "AES");

            String decryptedPassword = null;
            try {
                decryptedPassword = AESUtils.decryptPassword(user.getUserPassword(), secretKey);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            if (decryptedPassword.equals(oldUserPassword)){
                isTrue = true;
            }

        }

        return isTrue;
    }

    @Override
    public int updateUserInfo(User user) {
        return userMapper.updateUserInfo(user);
    }

    /**
     * 忘记密码
     * @param user
     * @return
     */
    @Override
    public int updatePsd(User user){

        int i = 0;

        //查找是否存在该手机号
        User user1 = userMapper.findByPhone(user.getPhone());
        if (user1 != null){
            //查看手机验证码是否正确
            Map<String,Object> map = (Map<String, Object>) redisTemplate.boundValueOps(user.getPhone()).get();

            if (map != null){
                String codeStr = (String) map.get("codeStr");
                System.out.println("redis中的codestr========="+codeStr);

                SmsService smsService = new SmsService();

                if ((user.getCodeStr() != null) && (codeStr != null)){
                    boolean isSuccess = smsService.verifyCode(user.getCodeStr(), codeStr);


                    if (isSuccess){

                        //查找是否已经注册过相同账号
                        User findUser = userMapper.findByUsername(user.getUsername());


                        if (findUser == null){

                            //生成密钥
                            SecretKey secretKey = null;
                            try {
                                secretKey = AESUtils.generateAESKey();
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }

                            //用户密码加密
                            String encryptedPassword = null;
                            try {
                                encryptedPassword = AESUtils.encryptPassword(user.getUserPassword(), secretKey);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }

                            user.setUserKey(secretKey.getEncoded());
                            user.setUserPassword(encryptedPassword);


                            int influenceRows = userMapper.updatePsd(user.getUserPassword(), user.getUserKey(), user.getPhone());

                            i = influenceRows;
                        }

                    }
                }
            }
        }
        return i;
    }

}
